/**
 消息列表
 **/

'use strict';

import React, {
    Component
} from 'react';
import {
    Text,
    ListView,
    RefreshControl,
    View,
    StyleSheet,
    Alert,
    Image,
    Button,
    InteractionManager,
    NativeModules,
    TouchableHighlight
} from 'react-native';
import NetUtil from '../../common/NetUtil';
import config from '../../config/config';
import backIcon from '../../image/back.png';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import moment from 'moment';
import Toast, {
    DURATION
} from 'react-native-easy-toast';

var TokenManager = NativeModules.TokenManagerPlugin;

import {getConfig, configkey} from '../../utils/NativeUtil'
import { NavigationActions } from 'react-navigation'

export default class MainView extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        header: <CLNavigatorHeader navigation={navigation} title="消息"/>,
    });

    constructor(props) {
        super(props);
        this.page = 1;
        this.size = 10;
        this.token = "";
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state = {
            isLoading: false,
            dataSource: ds,
            data: [],
            footText: "",
            hasMore: false,
        };
    }

    _backToFront() {
        const {
            navigator
        } = this.props;
        if (navigator) {
            navigator.pop();
        }
        ;
    }

    componentDidMount() {
        this.page = 1;
        const self = this;
        InteractionManager.runAfterInteractions(() => {
            let keys = `${configkey.UserToken}`;
            getConfig(keys, (values) => {
                self.token = values[configkey.UserToken];
                self.loadData(this.page, true);
            })
        });
    }

    startLoading = () => {
        this.setState({
            isLoading: true
        })
        this.setFootText("");
    }

    endLoading = () => {
        this.setState({
            isLoading: false
        })
    }

    setFootText = (text) => {
        this.setState({
            footText: text
        })
    }

    loadMore = () => {
        this.page = this.page + 1;
        this.loadData(this.page, false);
    }

    loadData = (page, isrefresh) => {
        var self = this;
        let url = '/s/message/list';

        const params = {
            token: this.token,
            page: this.page,
            size: this.size,
        };

        if (isrefresh) {
            this.startLoading();
        }


        NetUtil.postSign(config.apiUrl + url, params, function (res) {
            if (res.success) {
                let data = self.state.data.concat(res.data);
                self.setState({
                    data: data
                });
                if (res.data.length < self.size) {
                    self.setFootText("加载完成");
                    self.setState({
                        hasMore: false,
                    });
                } else {
                    self.setState({
                        hasMore: true,
                    });
                }
            } else {
                self.setFootText("加载失败，下拉重新加载");
            }

            if (isrefresh) {
                self.endLoading();
            }
        });
    }

    onRefresh() {
        this.page = 1;
        this.setState({
            data: []
        })
        this.loadData(this.page, true);
    }

    renderFooter = () => {
        return <View style={{margin: 10, flex: 1, flexDirection: 'row', justifyContent: 'center'}}>
            <Text style={{color: "gray"}}>{this.state.footText}</Text>
        </View>
    }


    catDetail(detail) {
        if (detail.url != undefined && detail.url != "") {
            let urls = detail.url.split("?");

            if (urls.length > 0) {
                let router = urls[0];
                let paramMap = {};

                if (urls.length > 1) {
                    let params = urls[1].split("&");
                    for (var i = 0; i < params.length; i++) {
                        let param = params[i];
                        let p = param.split("=");
                        if (p.length == 2) {
                            paramMap[p[0]] = p[1];
                        }
                    }
                }

                if (router == "/app/order/main") {
                    const index = values.index;
                    if (index != undefined){
                        this.setState({ selectedTab: 'order', title:"我的订单",orderIndex:parseInt(index)});
                    }
                } else if (values.routeKey == "/app/income/list"){
                    this.props.naviPush("applyrecord");
                }
                this.props.navigation.dispatch(NavigationActions.navigate({
                    routeName: router,
                    params: paramMap,
                    action: NavigationActions.navigate({routeName: 'ticketAdd'})
                }))
            }
        }
    }

    renderRow = (rowData) => {

        let datetime = moment.unix(rowData.time / 1000).format("YYYY-MM-DD HH:mm:ss");
        let urlview = '';
        // if (rowData.url == '') {
            urlview = null;
        // } else {
        //     urlview = (<Text style={{fontSize: 15, color: '#1a9b3b'}}>查看详情</Text>);
        // }

        return (
            <TouchableHighlight
                // onPress={ () => this.catDetail(rowData)}
                underlayColor='rgba(255,255,255,0)'>
                <View style={{flex: 1, flexDirection: 'column', padding: 10}}>
                    <Text style={{fontSize: 16, marginBottom: 10}}>{rowData.topic}</Text>
                    <Text style={{fontSize: 14, marginBottom: 10}}>{rowData.description}</Text>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between'}}>
                        <Text style={{fontSize: 15}}>{datetime}</Text>
                        {urlview}
                    </View>
                </View>
            </TouchableHighlight>
        );
    }

    renderSeparator = () => {
        return (<View style={{backgroundColor: '#eee', height: 2}}/>)
    }

    onEndReached = () => {
        if (this.state.hasMore == true) {
            this.loadMore();
        }
    }

    //全部删除
    _delAllMessage() {
        var self = this;
        let url = '/s/message/delete';
        const params = {
            token: this.token,
        };

        NetUtil.postSign(config.apiUrl + url, params, function (res) {
            if (res.success) {
                self.toastmessage('删除成功');
                self.page = 1;
                self.setState({
                    data: []
                });
                self.loadData(self.page, true);
            }
        });
    }

    toastmessage(message) {
        this.refs.toast.show(message, DURATION.LENGTH_LONG);
    }

    delDialog() {
        Alert.alert('是否删除', '删除则按确定,否则点击取消', [{
            text: '确定',
            onPress: () => this._delAllMessage()
        }, {
            text: '取消',
            onPress: () => console.log('Bar Pressed!')
        },])
    }


    render() {
        return (
            <View style={{flex: 1, flexDirection: 'column', backgroundColor: 'white'}}>
                <ListView
                    dataSource={
                        this.state.dataSource.cloneWithRows(this.state.data)
                    }
                    renderRow={
                        this.renderRow
                    }
                    renderSeparator={
                        this.renderSeparator
                    }
                    onEndReached={() => this.onEndReached()}
                    renderFooter={
                        this.renderFooter
                    }
                    enableEmptySections refreshControl={
                    <RefreshControl
                        onRefresh={() => this.onRefresh()}
                        refreshing={this.state.isLoading}
                        colors={['#0A9D35']}
                        enabled={true}
                    />
                }
                />
                <Toast ref="toast"/>
            </View>
        );
    }

}
